<?php

namespace App\Console\Commands\Plane\PlaneOrder;

use App\Events\Plane\PlaneOrder\PlaneOrderChangeNeedPayEvent;
use App\Events\Plane\PlaneOrder\PlaneOrderTicketedEvent;
use App\Events\Plane\PlaneOrder\PlaneOrderTicketFailedEvent;
use App\Models\Plane\PlaneOrders\PlaneOrder;
use App\Models\Plane\PlaneOrders\Repositories\Interfaces\PlaneOrderRepositoryInterface;
use Carbon\Carbon;
use Exception;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;

class ChangingOrderTryToChangedOrFailedOrWaitingPay extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'plane.changing.order:try_to_change';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '改签中的主动从服务商订单拉去订单状态,成功失败或者待支付';

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $planeOrderRepo  = app(PlaneOrderRepositoryInterface::class);
        $changing_orders = $planeOrderRepo->getChangingOrders();
        /**
         * @var PlaneOrder $order_info
         */
        foreach ($changing_orders as $order_info) {

            // 这里过滤 支付时间 10分钟内的订单那
            if ($order_info->provider_pay_at) {
                if (Carbon::now()->diffInMinutes($order_info->provider_pay_at) < 10) {
                    continue;
                }
            }

            try {
                $this->change($order_info);
                $this->change_failed($order_info);
                $this->waiting_pay($order_info);
            } catch (Exception $exception) {
                Log::error("计划任务拉取变更中的订单状态:{$order_info->getOrderSn()},失败,{$exception->getMessage()}");
            }
        }

    }


    private function change(PlaneOrder $order_info)
    {
        $changed_passengers = $order_info->OrderStrategy()->change_detail($order_info)->getChangedPassengers();
        if (!empty($changed_passengers)) {
            event(new PlaneOrderTicketedEvent($order_info, $changed_passengers));
        }
    }

    private function change_failed(PlaneOrder $order_info)
    {
        $change_failed_passengers = $order_info->OrderStrategy()->change_detail($order_info)->getChangeFailedPassengers();
        if (!empty($change_failed_passengers)) {
            event(new PlaneOrderTicketFailedEvent($order_info, $change_failed_passengers));
        }
    }

    private function waiting_pay(PlaneOrder $order_info)
    {
        $notifies = $order_info->OrderStrategy()->change_detail($order_info)->getChangeWaitingPayNotifies();
        foreach ($notifies as $notify) {
            event(new PlaneOrderChangeNeedPayEvent($order_info, $notify));
        }
    }
}
